import { ref, watch } from 'vue'
import { useLocalStorage } from '@vueuse/core'

export type Theme = 'light' | 'dark' | 'auto'

export const useTheme = () => {
  // 从本地存储获取主题设置，默认为auto
  const theme = useLocalStorage<Theme>('theme', 'auto')
  const isDark = ref(false)

  // 获取系统主题偏好
  const getSystemTheme = (): 'light' | 'dark' => {
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
  }

  // 应用主题
  const applyTheme = (newTheme: 'light' | 'dark') => {
    const html = document.documentElement
    
    if (newTheme === 'dark') {
      html.setAttribute('data-theme', 'dark')
      html.classList.add('dark')
      isDark.value = true
    } else {
      html.setAttribute('data-theme', 'light')
      html.classList.remove('dark')
      isDark.value = false
    }
  }

  // 更新主题
  const updateTheme = () => {
    if (theme.value === 'auto') {
      applyTheme(getSystemTheme())
    } else {
      applyTheme(theme.value)
    }
  }

  // 切换主题
  const toggleTheme = () => {
    if (theme.value === 'light') {
      theme.value = 'dark'
    } else if (theme.value === 'dark') {
      theme.value = 'auto'
    } else {
      theme.value = 'light'
    }
  }

  // 设置特定主题
  const setTheme = (newTheme: Theme) => {
    theme.value = newTheme
  }

  // 监听主题变化
  watch(theme, updateTheme, { immediate: true })

  // 监听系统主题变化
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
  mediaQuery.addEventListener('change', () => {
    if (theme.value === 'auto') {
      updateTheme()
    }
  })

  // 获取主题图标
  const getThemeIcon = () => {
    switch (theme.value) {
      case 'light':
        return '☀️'
      case 'dark':
        return '🌙'
      case 'auto':
        return '🔄'
      default:
        return '🔄'
    }
  }

  // 获取主题名称
  const getThemeName = () => {
    switch (theme.value) {
      case 'light':
        return '浅色模式'
      case 'dark':
        return '深色模式'
      case 'auto':
        return '跟随系统'
      default:
        return '跟随系统'
    }
  }

  return {
    theme,
    isDark,
    toggleTheme,
    setTheme,
    getThemeIcon,
    getThemeName,
    updateTheme
  }
}
